package wait_notify.guarded_suspension;

import lombok.extern.slf4j.Slf4j;
import util.Downloader;

import java.util.List;

@Slf4j(topic = "c.GuardedSuspension")
public class GuardedSuspension {
    // 线程1 等待 线程2 的下载结果
    public static void main(String[] args) {
        GuardObject guardObject = new GuardObject();
        new Thread(()->{
            log.debug("等待结果");
            List<String> list = (List<String>) guardObject.get(2000);
            log.debug("结果大小{}",list);
        },"t1").start();

        new Thread(()->{
            log.debug("执行下载");
            List<String> response = Downloader.download();
            guardObject.complete(response);
        },"t2").start();

    }

}

class GuardObject {
    //存放结果
    private Object response;
    //获取结果
    public Object get() {
        return get(Long.MAX_VALUE);
    }
    //带时限的等待
    public Object get(long timeout) {
        synchronized (this) {
            //开始时间
            long begin = System.currentTimeMillis();
            //经历的时间
            long passedTime = 0;
            while (response == null) {
                long waitTime = timeout-passedTime;
                //经历的时间超过了最大等待时间就退出循环
                if (waitTime<=0){
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passedTime =  System.currentTimeMillis() - begin;
            }
            return response;
        }
    }

    //产生结果
    public void complete(Object response){
        synchronized (this){
            this.response = response;
            this.notifyAll();
        }
    }

}
